package chat.client.controller;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class UserListCellRenderer extends JLabel implements ListCellRenderer<Object> {
    private ImageIcon defaultIcon; // 默认头像
    private int iconSize; // 头像大小

    public UserListCellRenderer(ImageIcon defaultIcon, int iconSize) {
        this.defaultIcon = defaultIcon;
        this.iconSize = iconSize;
        setOpaque(true);
        setHorizontalAlignment(LEFT);
        setVerticalAlignment(CENTER);
    }

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        setText(value.toString()); // 设置文本
        setIcon(scaleIcon(defaultIcon, iconSize)); // 设置缩放后的头像

        if (isSelected) {
            setBackground(list.getSelectionBackground());
            setForeground(list.getSelectionForeground());
        } else {
            setBackground(list.getBackground());
            setForeground(list.getForeground());
        }

        setEnabled(list.isEnabled());
        setFont(list.getFont());

        return this;
    }

    private ImageIcon scaleIcon(ImageIcon icon, int size) {
        Image image = icon.getImage();
        BufferedImage bufferedImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = bufferedImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(image, 0, 0, size, size, null);
        g2d.dispose();
        return new ImageIcon(bufferedImage);
    }
}